use axum::{
    extract::Extension,
    response::Json,
    http::StatusCode,
};
use anyhow::Result;
use serde_json::Value;
use crate::core::engine::{Task, OpsPanelCore};

pub async fn execute_script_handler(
    Extension(core): Extension<OpsPanelCore>,
    Json(task): Json<Task>,
) -> Result<Json<Value>, (StatusCode, String)> {
    core.execute_script(task)
        .await
        .map(Json)
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
}
use tokio::sync::Semaphore;

pub async fn execute_batch_handler(
    Extension(core): Extension<OpsPanelCore>,
    Json(tasks): Json<Vec<Task>>,
) -> Result<Json<Vec<Result<Value>>>, (StatusCode, Json<ErrorResponse>)> {
    if tasks.len() > 100 {
        return Err((StatusCode::BAD_REQUEST, Json(ErrorResponse {
            code: 400,
            message: "单次批量任务不得超过100个".into(),
        })));
    }

    let semaphore = Arc::new(Semaphore::new(10)); // 最大并发数10
    let results = join_all(tasks.into_iter().map(|task| {
        let permit = semaphore.clone().acquire_owned();
        async move {
            let _permit = permit.await;
            core.execute_script(task).await
        }
    })).await;

    Ok(Json(results))
}